<template>
    <div>
        <van-nav-bar
            title="聊天设置"
            left-text="返回"
            left-arrow
            @click-left="$router.go(-1)"/>
        <van-cell-group inset>
            <van-cell :title="showName" size="large">
                <template #icon>
                    <van-image width="40" height="40" center :src="friend.headImgUrl" />
                </template>
            </van-cell> 
            <van-cell title="发起群聊" icon="add-o" size="large" />
        </van-cell-group>
        <van-cell-group inset>
            <van-cell title="设置备注" icon="edit" size="large" @click="showRemarkDialog = true" />
            <van-cell title="设置分组" icon="cluster-o" size="large" @click="showGroupDialog = true" />
            <van-cell title="删除好友" icon="delete" size="large" @click="showDeleteDialog = true" />
        </van-cell-group>

        <!-- 添加备注弹窗 -->
        <van-dialog
            v-model="showRemarkDialog"
            title="设置备注"
            show-cancel-button
            @confirm="setRemark"
        >
            <van-field
                v-model="remarkText"
                placeholder="请输入备注名"
                :maxlength="20"
                show-word-limit
            />
        </van-dialog>

        <!-- 设置分组弹窗 -->
        <van-dialog
            v-model="showGroupDialog"
            title="设置分组"
            show-cancel-button
            @confirm="setGroup"
        >
            <div class="group-dialog-content">
                <van-radio-group v-model="selectedGroup">
                    <van-cell-group inset>
                        <van-cell v-for="group in groupList" :key="group.name" clickable @click="selectedGroup = group.name">
                            <template #icon>
                                <van-icon :name="getGroupIcon(group.name)" class="group-icon" />
                            </template>
                            <template #title>
                                <span>{{ group.name }}</span>
                            </template>
                            <template #right-icon>
                                <van-radio :name="group.name" />
                            </template>
                        </van-cell>
                    </van-cell-group>
                </van-radio-group>
            </div>
        </van-dialog>

        <!-- 删除好友确认弹窗 -->
        <van-dialog
            v-model="showDeleteDialog"
            title="删除好友"
            show-cancel-button
            @confirm="deleteFriend"
        >
            <div class="delete-dialog-content">
                <p>确定删除好友"{{ showName }}"吗？</p>
                <p class="delete-warning">删除后，将同时删除与该好友的聊天记录</p>
            </div>
        </van-dialog>
    </div>
</template>

<script>
    import { mapState, mapMutations } from 'vuex';
    import socket from '@/socket';
    export default {
        name: "MoreOperateView",
        data() {
            return {
                friend: '',
                showRemarkDialog: false,
                remarkText: '',
                showDeleteDialog: false,
                showGroupDialog: false,
                selectedGroup: '我的好友',
                // 默认分组
                defaultGroups: [
                    { name: '我的好友', default: true },
                    { name: '家人', default: false },
                    { name: '同学', default: false },
                    { name: '同事', default: false }
                ]
            }
        },
        computed: {
            ...mapState(['friendList', 'user']),
            showName() {
                // 获取当前好友信息
                const currentFriend = this.friendList.find(item => item.friendId._id === this.$route.query.user_id);
                // 如果有备注且备注不为空，则显示备注名
                if (currentFriend && currentFriend.remark && currentFriend.remark.trim() !== '') {
                    return currentFriend.remark;
                }
                // 否则显示原昵称
                return this.friend.nickname;
            },
            // 所有分组列表
            groupList() {
                // 从本地存储获取用户自定义分组
                const userGroups = JSON.parse(localStorage.getItem(`groups_${this.user.phone}`)) || [];
                
                // 合并默认分组和用户自定义分组
                return [...this.defaultGroups, ...userGroups].filter(group => !group.deleted);
            }
        },
        mounted() {
            let user_id = this.$route.query.user_id;
            this.friend = this.friendList.find(item => item.friendId._id === user_id)?.friendId;
            
            // 初始化备注文本
            const friend = this.friendList.find(item => item.friendId._id === user_id);
            if (friend) {
                this.remarkText = friend.remark || '';
                this.selectedGroup = friend.friendGroup || '我的好友';
            }
        },
        methods: {
            ...mapMutations(['upFriend']),
            // 根据分组名获取图标
            getGroupIcon(groupName) {
                const icons = {
                    '我的好友': 'friends-o',
                    '家人': 'home-o',
                    '同学': 'bookmark-o',
                    '同事': 'manager-o'
                };
                return icons[groupName] || 'star-o';
            },
            async setRemark() {
                try {
                    // 使用socket发送设置备注请求
                    socket.emit('set_remark', {
                        phone: this.user.phone,
                        friendId: this.$route.query.user_id,
                        remark: this.remarkText,
                    });

                    // 监听设置备注成功的响应
                    socket.once('setRemarkSuccess', (response) => {
                        if (response.code === 200) {
                            // 如果服务器返回了更新后的好友列表
                            if (response.friends && response.friends.length) {
                                // 清空当前store中的好友列表
                                this.friendList.splice(0, this.friendList.length);
                                // 用服务器返回的最新数据更新store
                                this.upFriend(response.friends);
                            } else {
                                // 如果服务器没有返回更新后的好友列表，则手动更新当前好友的备注
                                const friendIndex = this.friendList.findIndex(item => item.friendId._id === this.$route.query.user_id);
                                if (friendIndex !== -1) {
                                    // 使用Vue.set确保响应式更新
                                    this.$set(this.friendList[friendIndex], 'remark', this.remarkText);
                                }
                            }
                            this.$toast.success('设置备注成功');
                        }
                    });

                    // 监听设置备注失败的响应
                    socket.once('setRemarkError', (error) => {
                        console.error('设置备注失败:', error);
                        this.$toast.fail('设置备注失败');
                    });
                } catch (error) {
                    console.error('设置备注失败:', error);
                    this.$toast.fail('设置备注失败');
                }
            },
            
            async setGroup() {
                try {
                    // 使用socket发送设置分组请求并提供回调函数
                    socket.emit('update_friend_group', {
                        phone: this.user.phone,
                        friendId: this.$route.query.user_id,
                        groupName: this.selectedGroup
                    }, (response) => {
                        // 回调处理响应
                        if (response && response.code === 200) {
                            // 如果服务器返回了更新后的好友列表
                            if (response.friends && response.friends.length) {
                                // 清空当前store中的好友列表
                                this.friendList.splice(0, this.friendList.length);
                                // 用服务器返回的最新数据更新store
                                this.upFriend(response.friends);
                            } else {
                                // 如果服务器没有返回更新后的好友列表，则手动更新当前好友的分组
                                const friendIndex = this.friendList.findIndex(item => item.friendId._id === this.$route.query.user_id);
                                if (friendIndex !== -1) {
                                    // 使用Vue.set确保响应式更新
                                    this.$set(this.friendList[friendIndex], 'friendGroup', this.selectedGroup);
                                }
                            }
                            this.$toast.success('设置分组成功');
                        } else {
                            console.error('设置分组失败:', response);
                            this.$toast.fail(response?.message || '设置分组失败');
                        }
                    });
                } catch (error) {
                    console.error('设置分组失败:', error);
                    this.$toast.fail('设置分组失败');
                }
            },
            
            async deleteFriend() {
                try {
                    // 使用socket发送删除好友请求
                    socket.emit('del_friend', {
                        userPhone: this.user.phone,
                        friendId: this.$route.query.user_id,
                    });

                    // 监听删除好友成功的响应
                    socket.once('delFriendSuccess', (response) => {
                        if (response.code === 200) {
                            // 如果服务器返回了更新后的好友列表
                            if (response.friends && response.friends.length) {
                                // 清空当前store中的好友列表
                                this.friendList.splice(0, this.friendList.length);
                                // 用服务器返回的最新数据更新store
                                this.upFriend(response.friends);
                            } else {
                                // 手动从本地friendList中移除该好友
                                const friendIndex = this.friendList.findIndex(item => item.friendId._id === this.$route.query.user_id);
                                if (friendIndex !== -1) {
                                    this.friendList.splice(friendIndex, 1);
                                }
                            }
                            
                            this.$toast.success('删除好友成功');
                            // 导航到好友界面
                            this.$router.push('/friend');
                        }
                    });

                    // 监听删除好友失败的响应
                    socket.once('delFriendError', (error) => {
                        console.error('删除好友失败:', error);
                        this.$toast.fail('删除好友失败');
                    });
                } catch (error) {
                    console.error('删除好友失败:', error);
                    this.$toast.fail('删除好友失败');
                }
            }
        }
    }
</script>

<style lang="less" scoped>
    .van-cell-group {
        margin-top: 10px;
    }
    
    .delete-dialog-content {
        padding: 10px 20px;
        text-align: center;
        
        .delete-warning {
            color: #ff4d4f;
            font-size: 14px;
            margin-top: 5px;
        }
    }
    
    .group-dialog-content {
        max-height: 60vh;
        overflow-y: auto;
        padding: 10px 0;
        
        .group-icon {
            margin-right: 8px;
            font-size: 18px;
            color: #07C160;
        }
    }
</style>